/*
 * @lc app=leetcode.cn id=82 lang=typescript
 *
 * [82] 删除排序链表中的重复元素 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function deleteDuplicates(head: ListNode | null): ListNode | null {
    const map = new Map();
    while (head) {
        const count = map.get(head.val) || 0;
        map.set(head.val, count + 1);
        head = head.next;
    }
    let res = new ListNode();
    let pre: ListNode | null = null;
    for (let [k, v] of map) {
        if (v === 1) {
            if (!pre) {
                pre = new ListNode(k);
                res.next = pre;
            } else {
                pre.next = new ListNode(k);
                pre = pre.next;
            }
        }
    }
    return res.next;
};
// @lc code=end

